<template>
  <a-select
    class="w-[200px]"
    allowClear
    v-model="selected"
    :options="computedOptions"
    allow-search
    v-model:input-value="query.storeName"
    @search="handleSearch"
    @change="handleChange"
  ></a-select>
</template>

<script setup lang="ts">
import { listStore } from "@/api/service/store/store";
import { IStore } from "@/api/service/store/types";
import { ENUM_DATA_SCOPE } from "@/enum/system.enum";
import { IQuery, ITableResponse } from "@/interface/IAxios";

const selected = defineModel<string>();
const storeName = defineModel<string>("storeName");

const emit = defineEmits(["change"]);
const table = ref<ITableResponse<IStore>>({
  code: 0,
  msg: "",
  rows: [],
  total: 0
});

const query = ref<IQuery>({
  pageNum: 1,
  pageSize: 10,
  scope: ENUM_DATA_SCOPE.THIS_AND_ALL_SUB,
  storeName: ""
});
const loadOptions = async () => {
  const data = await listStore(query.value);
  table.value.rows = data.rows;
};
onMounted(async () => {
  loadOptions();
});
const handleSearch = () => {
  loadOptions();
};

const handleChange = (data: any) => {
  const target = table.value.rows.find((item) => {
    if (item.id === data) {
      return item;
    }
  });
  storeName.value = target?.storeName || "";
  emit("change");
};
const computedOptions = computed(() => {
  return table.value.rows.map((v) => {
    return {
      label: v.storeName,
      value: v.id
    };
  });
});
</script>

<style lang="scss" scoped></style>
